import React from 'react';
import EventEmiter from 'eventemitter3';
import co from 'co';
// import _ from 'lodash';
import { message, notification, Icon, Collapse } from 'antd';
import classNames from 'classnames';

import { createRecord } from '../../services/task';
import style from './window.less';
import TextOverflow from '../../components/TextOverflow';


const Panel = Collapse.Panel;

// 全局变量, 用于传递文件处理事件
const event = new EventEmiter();

// 渲染浮窗
class RecordWindow extends React.Component {
  constructor(p) {
    super(p);
    this.state = {
      files: {}, // 待处理的文件们
      isShow: false, // 窗口是否显示
      isDestroy: true, // 窗口
      activeKeys: [],
    };
    this.process = this.process.bind(this);
  }

  componentDidMount() {
    event.on('process', (filename, paragraph, taskId, cb) => {
      const isExsit = this.state.files[filename];
      if (!isExsit) {
        const newFile = {
          filename,
          paragraph,
          cb,
          isFinished: false,
          sentences: {},
          taskId,
        };
        const files = this.state.files;
        files[filename] = newFile;
        this.setState({
          files,
          isDestroy: false,
        }, () => {
          this.process(filename);
        });
      } else {
        message.warning(`文件${filename}已经在处理了`);
      }
    });
  }

  /**
   * 处理文件, 上传句子, 每一个文件的格式是 lineNumber  sentence, 行号和句子之间隔着一个空格
   * @param {string} filename 待处理的文件
   */
  process(filename) {
    const file = this.state.files[filename];
    if (!file) {
      return;
    }
    const { paragraph, taskId } = file;
    const lines = paragraph.split('\n');
    const self = this;
    co(function*() {
      for (const line of lines) {
        const words = line.split(' ');
        try {
          const lineNumber = words.shift();
          const sentence = words.join(' ');
          file.sentences[lineNumber] = {
            lineNumber,
            sentence,
            state: 'loading', // 是否处理中
          };
          self.setState({});
          // 上传文件
          try {
            const result = yield createRecord({
              lineNumber,
              content: { text: sentence },
              task: taskId,
            });
            if (result.status !== 1) {
              throw new Error(result.message);
            }
            file.sentences[lineNumber] = {
              lineNumber,
              sentence,
              state: 'success', // 是否处理中
            };
            self.setState({});
          } catch (e) {
            file.sentences[lineNumber] = {
              lineNumber,
              sentence,
              state: 'error', // 是否处理中
            };
            notification.error({
              message: '新建条目失败',
              description: `错误信息${e.message}`,
            });
            self.setState({});
          }
        } catch (e) {
          notification.error({
            message: '处理文件错误',
            description: `处理${line}错误，不符合格式`,
          });
        }
      }
      file.cb();
    });
  }

  render() {
    const { isDestroy, isShow, files } = this.state;
    const iconMap = {
      success: <Icon type="check" style={{ color: 'green' }} />,
      error: <Icon type="close" style={{ color: 'fail' }} />,
      loading: <Icon type="clock-circle" style={{ color: 'orange' }} />,
    };

    return (
      <div
        className={
        classNames({
          [style.window]: true,
          [style.show]: !isShow,
          [style.hidden]: isDestroy,
        })
      }
      >
        <div className={style.header}>
          <div
            className={style.button}
            onClick={() => this.setState({ isShow: !isShow })}
          >
            <Icon type={!isShow ? 'minus' : 'plus'} />
          </div>
          <div
            className={style.button}
            onClick={() => this.setState({ isDestroy: true })}
          >
            <Icon type="close" />
          </div>
        </div>
        <div className={style.body}>
          <Collapse bordered={false} defaultActiveKey={['0', '1', '2']}>
            {
              Object.keys(files).map((key, ind) => {
                const sentences = files[key].sentences;
                return (
                  <Panel header={key} key={ind}>
                    {
                      Object.keys(sentences).map((line) => {
                        return (
                          <div key={line} className={style['sentence-header']}>
                            <div className={style.lineNumber}>
                              {
                                line
                              }
                            </div>
                            <div>
                              <TextOverflow text={sentences[line].sentence} length={20} />
                            </div>
                            <div>
                              {
                                iconMap[sentences[line].state]
                              }
                            </div>
                          </div>
                        );
                      })
                    }
                  </Panel>
                );
              })
            }
          </Collapse>
        </div>
      </div>
    );
  }
}


/**
 * 发送到事件处理窗口
 * @param {string} filename 文件名
 * @param {string} paragraph 段落内容
 * @param {string|number} taskId 任务id
 * @param {function} cb 处理完成时的回调
 */
export const send = (filename, paragraph, taskId, cb) => {
  event.emit('process', filename, paragraph, taskId, cb);
};

export default RecordWindow;
